package data.platform.common.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicBoolean;

@Getter
@Setter
@NoArgsConstructor
public class AggregateItem {

    private Double avg;

    private Double max;

    private Double min;

    private Double sum;

    private Integer count;

    private Double latestValue;

    private LocalDateTime latestEventTime;

    private LocalDateTime maxEventTime;

    private LocalDateTime minEventTime;

    @JsonIgnore
    private AtomicBoolean dirty = new AtomicBoolean(true);

    @JsonIgnore
    private static final String KEY_PRE_NAME = "merge";

    @JsonIgnore
    public static final String KEY_SEPARATOR = "|";

    public AggregateItem(Double avg, Double max, Double min, Double sum, Integer count) {
        this.avg = avg;
        this.max = max;
        this.min = min;
        this.sum = sum;
        this.count = count;
    }

    public void compute(Double value, LocalDateTime eventTime) {
        latestValue = value;
        latestEventTime = eventTime;
        if (max.compareTo(value) < 0) {
            max = value;
            maxEventTime = eventTime;
        }
        if (min.compareTo(value) > 0) {
            min = value;
            minEventTime = eventTime;
        }
        sum += value;
        count++;
        avg = sum / count;
        dirty.compareAndSet(false, true);
    }

    // merge|day|metric|tagId
    public static String getKey(String metric, Integer tagId, String day) {
        return String.join(KEY_SEPARATOR, getPrefixKey(day), metric, tagId.toString());
    }

    public static String getPrefixKey(String day) {
        return String.join(KEY_SEPARATOR, KEY_PRE_NAME, day);
    }

    @Override
    public String toString() {
        return "AggregateItem{" +
                "avg=" + avg +
                ", max=" + max +
                ", min=" + min +
                ", sum=" + sum +
                ", count=" + count +
                ", latestValue=" + latestValue +
                ", latestEventTime=" + latestEventTime +
                ", MaxEventTime=" + maxEventTime +
                ", MinEventTime=" + minEventTime +
                ", dirty=" + dirty +
                '}';
    }

}
